package com.jiechuang.gateway.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

@SuppressWarnings("all")
@ConfigurationProperties(prefix = "jwt.config")
@Data
@Component
public class JWTUtil {
    //盐
    private String sault;
    //令牌有效时间，单位是毫秒(默认1分钟到期)
    private String jwtTime;
    //创建令牌
    public String createJWT(String id, String subject, List<String> roleCodes){
        //当前时间戳
        long now = System.currentTimeMillis();
        JwtBuilder builder = Jwts.builder()
                .setId(id)
                .setSubject(subject)
                .setIssuedAt(new Date())
                .signWith(SignatureAlgorithm.HS256, sault)
                .claim("roleCodes", roleCodes);//自定义属性
        if(Long.valueOf(jwtTime)>0){
            builder.setExpiration(new Date(now+Long.valueOf(jwtTime)));
        }
        return builder.compact();
    }
    //解析令牌
    public Claims parseJWT(String token){
        return Jwts.parser()
                .setSigningKey(sault)
                .parseClaimsJws(token)
                .getBody();

    }
}
